import styles from './index.module.less'
import type { Lesson } from '../../interface'
import classNames from 'classnames'
import { history } from 'umi'
import { SkeletonParagraphWrap } from '@/components/Common/Skeleton'

type Props = {
    lessons: Lesson[] | undefined
    currentLesson?: number
}

export const CourseList = (props: Props) => {
    const historyQuery = history.location.query

    const parseDuration = (duration: string) => {
        const nDuration = Number(duration ?? 0)
        const min = Math.floor(nDuration / 60)
        const sec = nDuration % 60
        return `${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')}`
    }

    const onItemClick = (lesson: Lesson) => {
        // 相同课程点击不做处理
        if (Number(lesson.lessonId) === props.currentLesson) return
        history.replace({ query: { ...historyQuery, lessonId: String(lesson.lessonId) } })
    }

    return (
        <div className={styles.courseList}>
            <SkeletonParagraphWrap animated lineCount={10} loading={props.lessons === undefined}>
                {props.lessons?.map(item => {
                    return (
                        <div
                            key={item.lessonId}
                            className={styles.courseItem}
                            onClick={() => {
                                onItemClick(item)
                            }}
                        >
                            <div
                                className={classNames({
                                    [styles.courseItem_icon_start]:
                                        props.currentLesson === Number(item.lessonId),
                                    [styles.courseItem_icon_pause]:
                                        props.currentLesson !== Number(item.lessonId),
                                })}
                            />
                            <span className={styles.courseItem_title}>{item.lessonName}</span>
                            <span className={styles.courseItem_time}>
                                {parseDuration(item.duration)}
                            </span>
                        </div>
                    )
                })}
            </SkeletonParagraphWrap>
        </div>
    )
}
